/**
 * IQIYI 短信接口
 */

const httpResult = require("../lib/httpResult");
const _ = require("lodash");
let router = require('koa-router')();
let moment = require('moment');
const crypto = require('crypto');
const MyEmitter = require('../lib/MyEmitter');
const sendMethod = require('../lib/hxtxChannel').send;
const utils = require("../lib/utils");
require('../pushReport');
require('../pushMo');

const status = {
  MT : {
    MISS_ACCOUNT : '-1001',
    MISS_TS : '-1002',
    MISS_TOKEN : '-1003',
    INVALID_TS : '-1004',
    TS_TIMEOUT : '-1005',
    INVALID_TOKEN : '-1006',
    AUTH_FAIL : '-1007',
    INVALID_ORI_IP : '-1008',
    ACCOUNT_BALANCE_NOT_ENOUGH : '-2001',
    ACCOUNT_CLOSED : '-2002',
    ACCOUNT_NOT_IN_SERVICE_TIME : '-2003',
    MISS_DEST : '-2301',
    INVALID_DEST : '-2302',
    MISS_CONTENT : '-2501',
    CONTENT_OVER_LENGTH : '-2502',
    CONTENT_NOT_MATCH : '-2505',
    DEST_OVER_LENGTH : '-2303'
  }
}

let sender = new MyEmitter(10, sendMethod, async (result) => {console.log(result)});
sender.name = 'iqiyi_sms_send_thread';
sender.startup();

router.get('/', async function (ctx, next) {
  ctx.state = {
    title: 'IQIYI'
  };

  await ctx.render('index', {
  });
})

async function commonValid(ctx){
  let body = ctx.request.body;
  let account = body.account;
  let ts = body.ts;
  let token = body.token;

  //valid acount
  ctx.assert(account, status.MT.MISS_ACCOUNT);
  ctx.assert(ts, status.MT.MISS_TS);
  ctx.assert(token, status.MT.MISS_TOKEN);
  let tsObj = moment(ts, 'YYYYMMDDHHmmss');
  ctx.assert(tsObj.isValid(), status.MT.INVALID_TS);
  ctx.assert(tsObj.add(5, 'm').isAfter(new Date()), status.MT.TS_TIMEOUT);

  let customer = await models.customer.findOne({account : account});
  if(!customer){
    throw '-1007'//鉴权失败
  }
  let sha1 = crypto.createHash('sha1');
  let tokenStr = sha1.update(account + customer.password + ts).digest('hex');
  ctx.assert(token === tokenStr, status.MT.INVALID_TOKEN);
  return customer;
}

async function doSubmit(ctx){
  // let admin = ctx.session.admin;
  log.info('submit info: ', ctx.request.body);

  let body = ctx.request.body;
  let reqLog = await models.mtRequestLog.create({body});

  let customerInfo = await commonValid(ctx);
  let account = body.account;

  let dest = body.dest;
  ctx.assert(dest, status.MT.MISS_DEST);
  let destArr = dest.split(',');
  ctx.assert(destArr.length <= 500, status.MT.DEST_OVER_LENGTH);
  let content = body.content;
  ctx.assert(content, status.MT.MISS_CONTENT);
  ctx.assert(content.length <= 500, status.MT.CONTENT_OVER_LENGTH);
  let contentArr = content.split('|||');
  ctx.assert(contentArr.length === 1 || contentArr.length === destArr.length, status.MT.CONTENT_NOT_MATCH);

  let ref = body.ref;
  let mtArr = destArr.map((mobile, i) => {
    let c = contentArr.length > 1 ? contentArr[i] : contentArr[0]
    //计算计费条数
    let fee = utils.feeCount(c);

    return {
      request_id : reqLog._id,
      account,
      mobile,
      content : c,
      charge_count : fee,
      ref,
      mt_msg_id : '',
      ext : body.ext || '',
    }
  })

  let records = await models.mtMsg.create(mtArr);
  records.forEach(r => r.password = customerInfo.password);
  sender.addTask(records);

  return {
    data : {ticket : reqLog._id},
    errorMsdn : {}
  };
}

router.get('/submit', httpResult.resp(doSubmit));

router.post('/submit', httpResult.resp(doSubmit));

router.post('/mt_report', httpResult.resp(async (ctx) => {
  await commonValid(ctx);
  let q = {cus_id: ctx.request.body.account, push_status : 0, try_times : {$lt : 3}, lock : ''};
  let update = {
    lock : ctx.request.body.token,
    push_status : 1,
    try_times: 1,
    type : 2
  }
  let rows = await models.customerReport.updateMany(q, {$set : update}).limit(50);
  let resp = [];
  if(rows.modifiedCount > 0){
    let results = await models.customerReport.find({lock : ctx.request.body.token});

    resp = results.map(r => {
      return {
        id : r.msg_id,
        dest : r.mobile,
        status : r.status,
        data : r.report_date,
        pieces : r.pieces,
        ext : r.ext,
        ticket : r.ticket,
        ref : r.ref,
        isoCode : r.iso_code
      }
    });
  }

  return {
    data : {
      reports : resp,
      errorMsdn : {}
    }
  }
}))

router.post('/mo', httpResult.resp(async (ctx) => {
  await commonValid(ctx);
  let q = {cus_id: ctx.request.body.account, push_status : 0, try_times : {$lt : 3}, lock : ''};
  let update = {
    lock : ctx.request.body.token,
    push_status : 1,
    try_times: 1,
    type : 2
  }
  let rows = await models.customerMo.updateMany(q, {$set : update}).limit(50);
  let resp = [];
  if(rows.modifiedCount > 0){
    let results = await models.customerMo.find({lock : ctx.request.body.token});

    resp = results.map(r => {
      return {
        dest : r.ext,
        src : r.mobile,
        content : r. content,
        date : r.mo_date
      }
    });
  }

  return {
    data : {
      mos : resp,
      errorMsdn : {}
    }
  }
}))

module.exports = router;

